﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Caching;

namespace OneStationFile.Common
{
    public class CacheHelper
    {
        public static bool _itemRemoved = false;
        public static DateTime _dateTime = DateTime.Now.AddDays(1);//默认缓存有效期
        public static  CacheItemRemovedCallback onRemove = new CacheItemRemovedCallback(RemovedCallback);
        public static readonly Cache cache = new Cache();
        /// <summary>
        /// 创建缓存，如果key存在则替换。
        /// </summary>
        /// <param name="key"></param>
        /// <param name="valObj"></param>
        public static void SetCache(string key,object valObj)
        {
            _itemRemoved = false;

            if (cache[key] == null)
            {
                cache.Add(key, valObj, null, _dateTime, TimeSpan.Zero, CacheItemPriority.High, onRemove);
            }
            else
            {
                cache.Insert(key, valObj);
            }
        }
        /// <summary>
        ///根据key 获取缓存的内容
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public static object GetCache(string key) {
            if (cache[key] == null)
            {
                return null;
            }
            return cache[key];
        }
        /// <summary>
        /// 回调函数
        /// </summary>
        /// <param name="k"></param>
        /// <param name="v"></param>
        /// <param name="r"></param>
        public static void RemovedCallback(String k, Object v, System.Web.Caching.CacheItemRemovedReason r)
        {
            _itemRemoved = true;
            var reason = r;
        }
        /// <summary>
        /// 删除某个key 对应的内容
        /// </summary>
        /// <param name="key"></param>
        public static void DeleteCache(string key) {
            cache.Remove(key);
        }
    }
}
